package groupware;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class GUser{
	public User user;
	public int accessLevel;
	
	public GUser(){
		UserService userService = UserServiceFactory.getUserService();
		user = userService.getCurrentUser();
	}
	private List<Entity> findUser(){
	    Query query = new Query("User");
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    query.addFilter("email", FilterOperator.EQUAL, user.getEmail().toString());
	    List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
        return users;
	}
	private boolean userExists(){
		return !findUser().isEmpty();
	}
	public boolean userAdd(){
		if(!userExists()){
	        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			Key userKey = KeyFactory.createKey("User", user.getEmail());
			Entity currentUser = new Entity("User", userKey);
	        currentUser.setProperty("email", user.getEmail());
	        currentUser.setProperty("accessLevel",0);	       
	        datastore.put(currentUser);
	        return true;
		}
		return false;
	}

	public boolean updateLevel(int accessLevel){
		if(userExists()){
	        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			List<Entity> users = findUser();
			Entity currentUser = users.get(0);
	        currentUser.setProperty("email", user.getEmail());
	        currentUser.setProperty("accessLevel", accessLevel);
	        this.accessLevel = accessLevel;
	        datastore.put(currentUser);
	        return true;
		}
		return false;
	}
	public long getLevel(){
		
		if(userExists()){
			return (Long) findUser().get(0).getProperty("accessLevel");
		}
		return 0;
	}
	private void getUser(){
		if(userExists()){
			Long al =  (Long) findUser().get(0).getProperty("accessLevel");
			accessLevel = al.intValue();
		}
	
	}
	public boolean loggedIn() {
		if(this.user != null){
			getUser();
			return true;
		}
		return false;
	}
}
